package com.dreamcode.anfeedreader.activity;

import java.util.List;

import com.dreamcode.anfeedreader.collectors.SettingsDAO;
import com.dreamcode.anfeedreader.collectors.SettingsDAOimpl;
import com.dreamcode.anfeedreader.modelClass.AccountObject;
import com.facebook.android.Facebook;
import com.facebook.android.LoginButton;

import twitter4j.IDs;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.User;
import twitter4j.UserList;
import twitter4j.http.AccessToken;
import twitter4j.http.RequestToken;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class AccountSettingsActivity extends Activity{
	private Button btnOk = null;
	private Button btnSync = null;
	private Button btnCancel = null;
	private Button btnConnect = null;
	private Button btnFbDelete = null;
	private Button btnTwConnect = null;
	private Button btnTwDelete = null;
	private WebView webView = null;
	private Twitter twitter = null;
	private Facebook facebook = null;
	private LoginButton mLoginButton = null;
	private String TWITTER_API_KEY = "ZyuteDnOzt4pIld95iPugQ";
	private static final String CONSUMER_KEY = "ZyuteDnOzt4pIld95iPugQ";
	private static final String CONSUMER_SECRET = "9tRFCaPvrYJ8jLKTAvnjFfK93OENw1FSpL9hkO89r0";
	private static final String APPLICATION_SECRET = "688d73da6ce54648b15565b889c413ae";
	private static final String APPLICATION_ID = "134594356558119";
	private RequestToken requestToken = null;
	private AccessToken accessToken = null;
	private String fbAccessToken;
	private String fbAccesExpires; 
	private SettingsDAOimpl settingsDAO = null;
	private List<AccountObject> accountObjects;
	private AccountObject accountObject = null;	
	private LinearLayout fbLayout = null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.accountsettings);
		initView();
	}
	public void initView(){
		settingsDAO = SettingsDAOimpl.getInstance();
		facebook = new Facebook();
		initAccounts();
		btnOk = (Button) findViewById(R.id.btnnewaccount);
		btnOk.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				fbAccessToken = facebook.getAccessToken();
				fbAccesExpires = String.valueOf(facebook.getAccessExpires());
				if(fbAccessToken!=null && fbAccesExpires!=null)
					settingsDAO.registerAccount(AccountSettingsActivity.this, "Facebook",fbAccessToken, fbAccesExpires);				
				Toast.makeText(AccountSettingsActivity.this, "Account creation was successful", Toast.LENGTH_SHORT).show();
				finish();
				
			}
		});
		btnCancel = (Button) findViewById(R.id.btncancelaccount);
		btnCancel.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				finish();
				
			}
		});
		btnSync = (Button) findViewById(R.id.btnsyncaccount);
		btnSync.setEnabled(false);
		btnSync.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
	
				
			}			
		});
		//btnConnect = (Button) findViewById(R.id.btnfbconnect);
		fbLayout = (LinearLayout) findViewById(R.id.fblayout);
		mLoginButton = new LoginButton(AccountSettingsActivity.this);        
        mLoginButton.init(facebook, new String[] {"publish_stream", "read_stream", "offline_access", "status_update"});
        mLoginButton.setText("Register");
        mLoginButton.setWidth(100);
        btnFbDelete = new Button(AccountSettingsActivity.this);
        btnFbDelete.setText("Delete");
        btnFbDelete.setWidth(100);
        btnFbDelete.setEnabled(false);
        if(settingsDAO.checkAccountExistence(AccountSettingsActivity.this, "Facebook")){
        	mLoginButton.setEnabled(false);
        	btnFbDelete.setEnabled(true);
        }else{
        	mLoginButton.setEnabled(true);        	
        }
        btnFbDelete.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				accountObject = settingsDAO.getAccoutSettings(AccountSettingsActivity.this, "Facebook");
				if(accountObject!=null){
					Builder yesNoBuilder = new AlertDialog.Builder(AccountSettingsActivity.this);
					yesNoBuilder.setTitle("Are you sure?").setPositiveButton("Ok", new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							settingsDAO.deleteAccount(AccountSettingsActivity.this, accountObject.getId());
							Toast.makeText(AccountSettingsActivity.this, "Account is deleted", Toast.LENGTH_SHORT).show();
							mLoginButton.setEnabled(true);
				        	btnFbDelete.setEnabled(false);
							//dialog.dismiss();
							//initView();
						}
					}).setNegativeButton("Cancel", null).show();
					
				}				
				initAccounts();	
				
			}
		});
        fbLayout.addView(mLoginButton);
        fbLayout.addView(btnFbDelete);
        
        /*LinearLayout lLi = (LinearLayout) findViewById(R.id.btnfb);
        lLi.addView(mLoginButton);*/
		/*btnConnect.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {				 
		         mLoginButton.init(facebook, new String[] {});		            
			}
		});*/
		btnTwConnect = (Button) findViewById(R.id.btntwconnect);
		btnTwDelete = (Button) findViewById(R.id.btntwdelete);
		btnTwDelete.setEnabled(false);
		if(settingsDAO.checkAccountExistence(AccountSettingsActivity.this, "Twitter")){
			btnTwConnect.setEnabled(false);
			btnTwDelete.setEnabled(true);
			btnSync.setEnabled(true);
		}else{
			btnTwConnect.setEnabled(true);
			btnSync.setEnabled(false);
		}
		btnTwConnect.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				twitter = new TwitterFactory().getInstance();
                twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);                
				try {
					requestToken = twitter.getOAuthRequestToken();
					webViewDialog(requestToken.getAuthorizationURL(), 0);				
				} catch (TwitterException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}                            
			}
		});		
		
		btnTwDelete.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				accountObject = settingsDAO.getAccoutSettings(AccountSettingsActivity.this, "Twitter");
				if(accountObject!=null){
					Builder yesNoBuilder = new AlertDialog.Builder(AccountSettingsActivity.this);
					yesNoBuilder.setTitle("Are you sure?").setPositiveButton("Ok", new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							settingsDAO.deleteAccount(AccountSettingsActivity.this, accountObject.getId());
							Toast.makeText(AccountSettingsActivity.this, "Account is deleted", Toast.LENGTH_SHORT).show();
							dialog.dismiss();
							initView();
						}
					}).setNegativeButton("Cancel", null).show();
					
				}				
				initAccounts();				
			}
		});
	
		
	}
	
	 public void webViewDialog(String url, final int type) {
	        LinearLayout container = new LinearLayout(AccountSettingsActivity.this);
	        container.setMinimumWidth(200);
	        container.setMinimumHeight(320);
	        webView = new WebView(AccountSettingsActivity.this);
	        webView.setMinimumWidth(200);
	        webView.setMinimumHeight(380);
	        webView.getSettings().setJavaScriptEnabled(true);
	        webView.setWebViewClient(new WebViewClient());
	        webView.loadUrl(url);
	        container.addView(webView);
	        Builder webDialog = new AlertDialog.Builder(AccountSettingsActivity.this);
	        webDialog.setView(container).setTitle("Web Settings").setPositiveButton("Ok",
	                new DialogInterface.OnClickListener() {

	                    @Override
	                    public void onClick(DialogInterface dialog, int which) {	                    	
	                        if (type == 0) {
	                        	twitterPinCodeDialog();
	                        	dialog.dismiss();
	                        }
	                        //dialog.dismiss();
	                    }
	                }).show();
	    }
	 
	 public void twitterPinCodeDialog(){
		 LinearLayout pinHolder = new LinearLayout(AccountSettingsActivity.this);
		 pinHolder.setGravity(Gravity.CENTER);
     	final EditText editPinCode = new EditText(AccountSettingsActivity.this);
     	editPinCode.setGravity(Gravity.CENTER);
     	editPinCode.setHint("Pin Code");
     	editPinCode.setWidth(200);
     	pinHolder.addView(editPinCode);
     	
     	Builder pinBuilder = new AlertDialog.Builder(AccountSettingsActivity.this);
     	pinBuilder.setView(pinHolder).setTitle("Twitter Pin Code Entry").setMessage("Please enter displayed twitter code into the field")
     	.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
						if (editPinCode.getText().toString() != null
								&& !editPinCode.getText().toString().equals("")) {
							try {
								accessToken = twitter.getOAuthAccessToken(requestToken, editPinCode.getText().toString());
								Log.i("Access Token:",accessToken.getToken());
								Log.i("Access Secret:",accessToken.getTokenSecret());
								settingsDAO.registerAccount(AccountSettingsActivity.this, "Twitter", accessToken.getToken(), accessToken.getTokenSecret());
								initView();
							} catch (TwitterException te) {
								if (401 == te.getStatusCode()) {
									System.out
											.println("Unable to get the access token.");
								} else {
									te.printStackTrace();
								}

							}
						}else{
							Toast.makeText(AccountSettingsActivity.this, "Pin code is required", Toast.LENGTH_SHORT).show();
							dialog.dismiss();
							twitterPinCodeDialog();							
						}

					}
			}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					Toast.makeText(AccountSettingsActivity.this, "To share your news please complete login next time", Toast.LENGTH_LONG).show();
					dialog.dismiss();
				}
			}).show();
     	
	 }
	 
	 public void initAccounts(){
		 accountObjects = settingsDAO.getAllAccounts(AccountSettingsActivity.this);		 
	 }
	 
}
